/**
 * Classname :AccountAction.java
 *
 */

package com.history.web.action.article;

import java.util.List;

import com.history.business.ArticleManager;
import com.history.common.RandomHelper;
import com.history.domain.bean.Article;
import com.history.domain.model.ArticleModel;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 
 * @author Ho.Viet.Duan Created Dec 27, 2011
 */
public class ArticleAction extends ActionSupport implements
		ModelDriven<ArticleModel> {

	ArticleManager articleManager;
	public void setArticleManager(ArticleManager articleManager) {
		this.articleManager = articleManager;
	}

	ArticleModel model = new ArticleModel();
	
	@Override
	public ArticleModel getModel() {
		// TODO Auto-generated method stub
		return model;
	}
	
	public String listArticle() throws Exception {
		try {
			List<Article> articleList = articleManager.findAll();
			model.setArticleList(articleList);
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		}
		
		return SUCCESS;
	}
	

	public String getArticle() throws Exception {
		try {
			String id = model.getArticle().getId();
			Article article = articleManager.findById(id);
			model.setArticle(article);
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		}
		
		return SUCCESS;
	}
	
	public String editArticle() throws Exception {
		try {
			Article article = model.getArticle();
			if (article != null) {
				String id = model.getArticle().getId();
				Article articleTemp = articleManager.findById(id);
				if (articleTemp.getSysKey().equals(article.getSysKey())) {
					String key = RandomHelper.generateRandomKey();
					article.setSysKey(key);
					articleManager.updateArticle(article);	
				} else {
					model.setMessage("Article has been modified!");
					return INPUT;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		}
		
		return SUCCESS;
	}
	
}